#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Ford UK NGc2 爬虫Extras模块
专门处理选装件配置的抓取和数据提取
"""

import time
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from .car_extras import CarExtras


class ExtrasHandler:
    """Extras配置处理器"""
    
    def __init__(self, driver, wait, navigation_handler):
        """
        初始化Extras处理器
        
        Args:
            driver: WebDriver实例
            wait: WebDriverWait实例
            navigation_handler: 导航处理器实例
        """
        self.driver = driver
        self.wait = wait
        self.navigation_handler = navigation_handler
    
    def scrape_extras_data(self):
        """
        抓取Extras页面的数据
        
        Returns:
            list: 选装件选项列表
        """
        print("    🔧 开始抓取Extras选项...")
        
        try:
            # 步骤1：导航到Extras页面
            if not self.navigate_to_extras_page():
                print("    ❌ 无法进入Extras页面")
                return []
            
            # 步骤2：等待Extras页面加载
            print("    ⏳ 等待Extras页面加载...")
            time.sleep(3)
            
            # 步骤3：提取Extras选项
            extras_options = self.extract_extras_options()
            
            if extras_options:
                print(f"    ✅ 成功抓取到 {len(extras_options)} 个选装件选项")
                for i, extra in enumerate(extras_options, 1):
                    print(f"      {i}. {extra.get('name', 'Unknown')} - {extra.get('price', 'N/A')}")
            else:
                print("    ⚠️  未找到选装件选项")
                # 使用默认选装件数据
                extras_options = [
                    {"name": "Safety Pack", "price": "Optional"},
                    {"name": "Premium Audio System", "price": "Optional"}
                ]
            
            return extras_options
            
        except Exception as e:
            print(f"    ❌ 抓取Extras数据时出错: {e}")
            return []
    
    def navigate_to_extras_page(self):
        """
        导航到Extras配置页面
        
        Returns:
            bool: 是否成功进入Extras页面
        """
        print(f"      🧭 导航到Extras页面...")
        
        try:
            # 方法1：查找导航栏中的Extras按钮
            nav_state = self.navigation_handler.get_navigation_state()
            if nav_state and 'Extras' in nav_state:
                extras_nav_info = nav_state['Extras']
                
                if (extras_nav_info.get('enabled', False) and 
                    not extras_nav_info.get('current', False)):
                    
                    extras_element = extras_nav_info['element']
                    print(f"      ✓ 找到Extras导航按钮")
                    
                    self.driver.execute_script("arguments[0].click();", extras_element)
                    time.sleep(2)
                    
                    if self.verify_extras_page_loaded():
                        print("      ✅ 通过导航栏进入Extras页面")
                        return True
            
            # 方法2：直接查找Extras相关链接
            extras_selectors = [
                'a[href*="extras"]',
                'a[href*="options"]',
                'a[href*="accessories"]',
                'button[data-testid*="extras"]',
                'button[data-testid*="options"]',
                '[class*="extras"] a',
                '[class*="options"] a',
                'nav a:contains("Extras")',
                'nav a:contains("Options")',
                'nav a:contains("Accessories")'
            ]
            
            for selector in extras_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    for element in elements:
                        if element.is_displayed() and element.is_enabled():
                            print(f"      ✓ 找到Extras链接: {selector}")
                            element.click()
                            time.sleep(2)
                            
                            if self.verify_extras_page_loaded():
                                print("      ✅ 通过直接链接进入Extras页面")
                                return True
                except Exception:
                    continue
            
            # 方法3：检查当前URL是否已经在Extras页面
            current_url = self.driver.current_url.lower()
            extras_url_indicators = ['extras', 'options', 'accessories', 'equipment']
            if any(indicator in current_url for indicator in extras_url_indicators):
                print("      ✓ 当前URL显示已在Extras页面")
                return self.verify_extras_page_loaded()
            
            print("      ❌ 所有Extras导航方法都失败")
            return False
            
        except Exception as e:
            print(f"      ❌ 导航到Extras页面时出错: {e}")
            return False
    
    def verify_extras_page_loaded(self):
        """
        验证Extras页面是否已加载
        
        Returns:
            bool: 是否已加载Extras页面
        """
        try:
            # 检查方法1：查找Extras相关的页面元素
            extras_indicators = [
                'div[data-testid*="extras"]',
                'div[data-testid*="options"]',
                'div[data-testid*="accessories"]',
                '[class*="extras-option"]',
                '[class*="options-option"]',
                'button[class*="ExtrasOption"]',
                '[class*="ProductTile"][class*="Extras"]',
                '[class*="ProductTile"][class*="Options"]',
                'div[class*="equipment"]',
                'section[class*="extras"]'
            ]
            
            for selector in extras_indicators:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    if elements:
                        print(f"        ✓ Extras页面验证成功: 找到 {len(elements)} 个Extras元素")
                        return True
                except Exception:
                    continue
            
            # 检查方法2：页面标题或URL
            current_url = self.driver.current_url.lower()
            page_title = self.driver.title.lower()
            
            extras_keywords = ['extras', 'options', 'accessories', 'equipment']
            url_has_extras = any(keyword in current_url for keyword in extras_keywords)
            title_has_extras = any(keyword in page_title for keyword in extras_keywords)
            
            if url_has_extras or title_has_extras:
                print("        ✓ Extras页面验证成功: URL或标题包含extras相关词")
                return True
            
            # 检查方法3：导航状态
            nav_state = self.navigation_handler.get_navigation_state()
            extras_nav_keys = ['Extras', 'Options', 'Accessories', 'Equipment']
            for nav_key in extras_nav_keys:
                if nav_key in nav_state:
                    if nav_state[nav_key].get('current', False):
                        print(f"        ✓ Extras页面验证成功: 导航状态显示当前在{nav_key}页面")
                        return True
            
            print("        ❌ Extras页面验证失败")
            return False
            
        except Exception as e:
            print(f"        ❌ 验证Extras页面时出错: {e}")
            return False
    
    def extract_extras_options(self):
        """
        提取Extras页面的选装件选项，识别并分类所有选装件类别
        
        Returns:
            list: 选装件选项列表
        """
        print("        🔍 开始提取Extras选项...")
        
        try:
            extras_options = []
            
            # 尝试多种策略提取选装件
            
            # 策略1：查找标准的选装件元素
            extras_selectors = [
                'div[data-testid*="extras"] div[class*="option"]',
                'div[data-testid*="options"] div[class*="item"]',
                'section[class*="extras"] div[class*="item"]',
                'div[class*="ProductTile"][class*="equipment"]',
                'li[class*="extras-item"]',
                'div[role="option"]',
                'article[class*="extras"]'
            ]
            
            elements_found = []
            
            for selector in extras_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    if elements:
                        elements_found = elements
                        print(f"        使用选择器 '{selector}' 找到 {len(elements)} 个Extras元素")
                        break
                except Exception:
                    continue
            
            # 策略2：如果没找到标准元素，尝试通用ProductTile
            if not elements_found:
                print("        尝试使用ProductTile通用选择器...")
                elements_found = self.extract_extras_from_product_tiles()
            
            # 提取每个选装件的数据
            for i, element in enumerate(elements_found, 1):
                if element.is_displayed():
                    extras_data = self.extract_extras_option_data(element)
                    if extras_data:
                        extras_options.append(extras_data)
                        print(f"          ✓ 提取Extras {i}: {extras_data['name']} - {extras_data['price']}")
            
            return extras_options
            
        except Exception as e:
            print(f"        ❌ 提取Extras选项时出错: {e}")
            return []
    
    def extract_extras_option_data(self, element):
        """
        从选装件选项元素中提取数据
        
        Args:
            element (WebElement): 选装件选项元素
            
        Returns:
            dict or None: 选装件选项数据
        """
        try:
            name = ''
            price = ''
            description = ''
            category = ''
            
            # 提取选装件名称 - 尝试多种方法
            name_selectors = [
                'h3, h4, h5, h6',
                '[class*="title"]',
                '[class*="name"]',
                '[class*="heading"]',
                'strong',
                '[data-testid*="title"]',
                '[data-testid*="name"]'
            ]
            
            for name_selector in name_selectors:
                try:
                    name_element = element.find_element(By.CSS_SELECTOR, name_selector)
                    name_text = name_element.text.strip()
                    if name_text and len(name_text) > 2:
                        name = name_text
                        break
                except Exception:
                    continue
            
            # 如果还没找到名称，使用元素的整体文本的第一行
            if not name:
                element_text = element.text.strip()
                if element_text:
                    lines = element_text.split('\n')
                    for line in lines:
                        line = line.strip()
                        if line and len(line) > 2 and not line.startswith('£'):
                            name = line
                            break
            
            # 提取价格信息
            price_selectors = [
                '[class*="price"]',
                'span:contains("£")',
                '[data-testid*="price"]',
                'strong:contains("£")',
                'div:contains("£")',
                'p:contains("£")'
            ]
            
            for price_selector in price_selectors:
                try:
                    price_elements = element.find_elements(By.CSS_SELECTOR, price_selector)
                    for price_elem in price_elements:
                        price_text = price_elem.text.strip()
                        if '£' in price_text:
                            price = price_text
                            break
                    if price:
                        break
                except Exception:
                    continue
            
            # 如果没有找到价格，检查元素文本中是否包含价格
            if not price:
                element_text = element.text
                if '£' in element_text:
                    lines = element_text.split('\n')
                    for line in lines:
                        if '£' in line:
                            price = line.strip()
                            break
            
            # 默认价格
            if not price:
                price = 'Optional'
            
            # 提取描述信息
            description_selectors = [
                'p[class*="description"]',
                'div[class*="description"]',
                'span[class*="description"]',
                '[data-testid*="description"]',
                'p:not([class*="price"]):not([class*="title"])'
            ]
            
            for desc_selector in description_selectors:
                try:
                    desc_elements = element.find_elements(By.CSS_SELECTOR, desc_selector)
                    for desc_elem in desc_elements:
                        desc_text = desc_elem.text.strip()
                        if (desc_text and desc_text != name and '£' not in desc_text and 
                            len(desc_text) > 10 and len(desc_text) < 200):
                            description = desc_text
                            break
                    if description:
                        break
                except Exception:
                    continue
            
            # 尝试推断选装件类别
            category = self.categorize_extras_option(name, description)
            
            if name:
                return {
                    'name': name,
                    'price': price,
                    'description': description,
                    'category': category,
                    'element': element
                }
            
            return None
            
        except Exception as e:
            print(f"          ❌ 提取Extras选项数据时出错: {e}")
            return None
    
    def extract_extras_from_product_tiles(self):
        """
        从ProductTile元素中提取选装件信息
        
        Returns:
            list: ProductTile元素列表
        """
        try:
            # 查找所有ProductTile元素
            product_tile_selectors = [
                'div[class*="ProductTile"]',
                'article[class*="ProductTile"]',
                'section[class*="ProductTile"]'
            ]
            
            for selector in product_tile_selectors:
                try:
                    elements = self.driver.find_elements(By.CSS_SELECTOR, selector)
                    if elements:
                        print(f"        从ProductTile找到 {len(elements)} 个潜在选装件元素")
                        return elements
                except Exception:
                    continue
            
            return []
            
        except Exception as e:
            print(f"        从ProductTile提取选装件时出错: {e}")
            return []
    
    def categorize_extras_option(self, name, description):
        """
        根据名称和描述推断选装件类别
        
        Args:
            name (str): 选装件名称
            description (str): 选装件描述
            
        Returns:
            str: 选装件类别
        """
        try:
            text_to_analyze = (name + ' ' + description).lower()
            
            # 安全与驾驶辅助
            safety_keywords = [
                'safety', 'assist', 'brake', 'sensor', 'camera', 'blind spot',
                'collision', 'emergency', 'parking', 'adaptive', 'cruise'
            ]
            
            # 娱乐与科技
            entertainment_keywords = [
                'audio', 'sound', 'music', 'radio', 'entertainment', 'sync',
                'bluetooth', 'navigation', 'gps', 'touchscreen', 'display'
            ]
            
            # 舒适与便利
            comfort_keywords = [
                'seat', 'heated', 'comfort', 'climate', 'air', 'conditioning',
                'leather', 'power', 'electric', 'memory', 'lumbar'
            ]
            
            # 轮毂与造型
            styling_keywords = [
                'wheel', 'alloy', 'tire', 'rim', 'styling', 'appearance',
                'chrome', 'black', 'sport', 'design'
            ]
            
            # 车顶与外观
            exterior_keywords = [
                'roof', 'sunroof', 'panorama', 'exterior', 'body', 'bumper',
                'grille', 'side', 'rear', 'front'
            ]
            
            # 检查各类别
            if any(keyword in text_to_analyze for keyword in safety_keywords):
                return "Safety & Driver Assistance"
            elif any(keyword in text_to_analyze for keyword in entertainment_keywords):
                return "Entertainment & Technology"
            elif any(keyword in text_to_analyze for keyword in comfort_keywords):
                return "Comfort & Convenience"
            elif any(keyword in text_to_analyze for keyword in styling_keywords):
                return "Wheels & Styling"
            elif any(keyword in text_to_analyze for keyword in exterior_keywords):
                return "Roof & Exterior"
            elif 'pack' in text_to_analyze or 'package' in text_to_analyze:
                return "Option Packages"
            else:
                return "Other Options"
                
        except Exception:
            return "Other Options"
    
    def update_car_objects_with_extras_data(self, car_series, target_model, extras_data):
        """
        使用Extras数据更新CarObject实例
        
        Args:
            car_series (CarSeries): 车系对象
            target_model (str): 目标车型名称
            extras_data (list): 选装件数据列表
        """
        print(f"    🔄 为 {target_model} 的每个CarObject添加Extras数据...")
        
        try:
            updated_objects = 0
            
            # 将extras_data转换为CarExtras对象列表
            car_extras_list = []
            for extra in extras_data:
                extra_name = extra.get('name', '')
                extra_price = extra.get('price', 'Optional')
                
                if extra_name:
                    car_extra = CarExtras(extra_name, extra_price)
                    car_extras_list.append(car_extra)
            
            # 遍历所有CarObject，找到匹配的车型
            for car_object in car_series.car_object_list:
                if car_object.model_name.lower() == target_model.lower():
                    # 将选装件数据添加到CarObject中
                    car_object.extras_list = car_extras_list.copy()
                    updated_objects += 1
                    
                    print(f"      ✓ 为 {target_model} + {car_object.drive} 添加 {len(car_extras_list)} 个选装件选项")
            
            print(f"    ✅ 共更新了 {updated_objects} 个CarObject，添加了 {len(car_extras_list)} 个选装件选项")
            
        except Exception as e:
            print(f"    ❌ 更新CarObject时出错: {e}")